package com.dlc.felear.xiaoensale.customView;


import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.dlc.felear.xiaoensale.R;
import com.dlc.felear.xiaoensale.constant.Constant;
import com.dlc.felear.xiaoensale.entity.Operator;

import java.util.ArrayList;
import java.util.List;

public class ProgressView extends View {
    private static final String TAG = "ProcessView";

    public static final int MODE_BOTTOM = 1;
    public static final int MODE_TOP = 2;
    private static final int DEFAULT_HEIGHT = 200;//默认高度

    private final int defaultColor = Color.rgb(204, 204, 204);
    private final int defaultReachedColor = Color.rgb(66, 145, 241);
    private final int defaultLineColor = Color.rgb(204, 204, 204);


    private Paint mStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private Paint mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private Paint mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
    private Paint mLinePaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
    private RectF mLineRect = new RectF();
    private Rect mTextRect = new Rect();
    private Rect mTextRect1 = new Rect();

    private String mContentText;

    private float mGap;
    private float mMargin;
    private float mTextSize;
    private float mStepTextSize;
    private float mLineHeight;
    private float mStrokeWidth;//外圈的宽度
    private float mCenterRadius;//内圈半径
    private float mStrokeRadius;//外圈半径
    private float mCircleHeight;//绘制圆圈的高度
    private float mTextY;//绘制文案的Y值

    private int mMode;
    private int mProgress;
    private int mMaxCount;
    private int mDefaultColor;
    private int mReachedColor;
    private int mTextColor;
    private int mLineColor;
    private int mWidth;
    private int mHeight;

    private boolean mDrawLine;
    private boolean mDrawText;
    private boolean mDrawText1;

    private List<CharSequence> mSteps = new ArrayList<>();
    private List<CharSequence> mSteps1 = new ArrayList<>();


    public ProgressView(Context context) {
        this(context, null);
    }

    public ProgressView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ProgressView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        float defaultStrokeRadius = dp2px(10);
        float defaultCenterRadius = dp2px(5);
        float defaultStrokeWidth = dp2px(2);
        float defaultLineHeight = dp2px(2);
        float defaultGap = dp2px(1);
        float defaultMargin = dp2px(3);
        float defaultTextSize = sp2px(10);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ProgressView, defStyleAttr, 0);
        mMaxCount = a.getInt(R.styleable.ProgressView_max, 1);
        mProgress = a.getInt(R.styleable.ProgressView_progress, 0);
        mLineColor = a.getColor(R.styleable.ProgressView_lineColor, defaultLineColor);
        mDefaultColor = a.getColor(R.styleable.ProgressView_defaultColor, defaultColor);
        mReachedColor = a.getColor(R.styleable.ProgressView_reachedColor, defaultReachedColor);
        mTextColor = a.getColor(R.styleable.ProgressView_contextTextColor, defaultColor);
        mLineHeight = a.getDimension(R.styleable.ProgressView_lineHeight, defaultLineHeight);
        mStrokeWidth = a.getDimension(R.styleable.ProgressView_strokeWidth, defaultStrokeWidth);
        mCenterRadius = a.getDimension(R.styleable.ProgressView_centerRadius, defaultCenterRadius);
        mStrokeRadius = a.getDimension(R.styleable.ProgressView_strokeRadius, defaultStrokeRadius);
        mTextSize = a.getDimension(R.styleable.ProgressView_contextTextSize, defaultTextSize);
        mStepTextSize = a.getDimension(R.styleable.ProgressView_stepTextSize, defaultTextSize);
        mContentText = a.getString(R.styleable.ProgressView_contentText);
        mGap = a.getDimension(R.styleable.ProgressView_gap, defaultGap);
        mMargin = a.getDimension(R.styleable.ProgressView_textMargin, defaultMargin);
        mMode = a.getInt(R.styleable.ProgressView_indicator_mode, MODE_BOTTOM);
        a.recycle();

        init();
        //修正一些临界值
        if (mProgress > mMaxCount) {
            mProgress = mMaxCount;
        }
        if (mCenterRadius >= mStrokeRadius) {
            mCenterRadius = mStrokeRadius;
        }
        if (mGap < 0) {
            mGap = 0;
        }
        mDrawLine = mMaxCount > 1;

    }

    private void init() {
        mStrokePaint.setStyle(Paint.Style.STROKE);
        mStrokePaint.setStrokeWidth(mStrokeWidth);
        mStrokePaint.setColor(mDefaultColor);
        mCenterPaint.setStyle(Paint.Style.FILL);
        mCenterPaint.setColor(mReachedColor);
        mLinePaint.setColor(mLineColor);
        mTextPaint.setColor(mTextColor);
        mTextPaint.setTextSize(mStepTextSize);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(measure(widthMeasureSpec, true), measure(heightMeasureSpec, false));
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = w;
        mHeight = h;
        calcSize();
    }

    public void setCurrentIndex(int size, int index) {
        try {
            mMaxCount = size;
            mProgress = index;
            invalidate();
        }catch (Exception e){
           e.printStackTrace();
        }
    }

    public String getCurrentStep(int index) {
        if (index >= mSteps.size()) {
            return "";
        }
        return "当前步骤:" + mSteps.get(index).toString();
    }

    private void calcSize() {
        int usefulHeight = mHeight - getPaddingBottom() - getPaddingTop();
        if (checkSteps()) {
            mDrawText = true;
            mDrawText1 = true;
            mTextPaint.getTextBounds(String.valueOf(mSteps.get(0)), 0, String.valueOf(mSteps.get(0)).length(), mTextRect);
            float center = (mTextPaint.ascent() + mTextPaint.descent()) / 2.0f;
            if (mMode == MODE_BOTTOM) {
                mCircleHeight = usefulHeight / 2.0f - mTextSize;
                mTextY = mCircleHeight - center + mStrokeRadius + mTextSize / 2.0f + dp2px(mMargin);
            } else {
                mCircleHeight = usefulHeight / 2.0f + mTextSize;
                mTextY = mCircleHeight - center - mStrokeRadius - mTextSize / 2.0f - dp2px(mMargin);
            }
        } else {
            mDrawText = false;
            mDrawText1 = false;
            mCircleHeight = usefulHeight / 2.0f;
        }
        if (mDrawLine) {
            float lineHeight = dp2px(mLineHeight);
            if (mMode == MODE_BOTTOM) {
                mLineRect.top = mCircleHeight - lineHeight / 2.0f;
                mLineRect.bottom = mCircleHeight + lineHeight / 2.0f;
            } else {
                mLineRect.top = mCircleHeight - lineHeight / 2.0f;
                mLineRect.bottom = mCircleHeight + lineHeight / 2.0f;
            }
        }
    }

    private boolean checkSteps() {
        return !(mSteps == null || mSteps.size() < 1 || mSteps.size() != mMaxCount);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mMaxCount < 1) {
            return;
        }
//        int height = getHeight() - getPaddingBottom() - getPaddingTop();
        int usefulWidth = mWidth - getPaddingLeft() - getPaddingRight();//可用
        float g = (usefulWidth / (mMaxCount));
        //起始点
        float startX = getPaddingLeft();
        startX += g / 2.0f;//这里绘制不能超出paddingRight
        for (int iLoop = 0; iLoop < mMaxCount; iLoop++) {
            float drawX = startX + (iLoop * g);
            //已完成进度的色值
            mStrokePaint.setColor(iLoop <= mProgress - 1 ? mReachedColor : mDefaultColor);
            if (mDrawText1) {
                CharSequence c = mSteps1.get(iLoop);
                mTextPaint.getTextBounds(c.toString(), 0, c.toString().length(), mTextRect);
                canvas.drawText(c.toString(), drawX - mTextRect.width() / 2.0f, mCircleHeight-16, mTextPaint);
                Log.e(TAG,"步骤:"+c.toString());
            }
            canvas.drawCircle(drawX, mCircleHeight, mStrokeRadius, mStrokePaint);
            //绘制进度位置
            if (iLoop <= mProgress - 1) {
                canvas.drawCircle(drawX, mCircleHeight, mCenterRadius, mCenterPaint);
            }
            //绘制文字
            if (mDrawText) {
                CharSequence c = mSteps.get(iLoop);
                drawTextVer(c.toString(),canvas,drawX);
                Log.e(TAG,"步骤:"+c.toString());
            }
        }
        //绘制连接线
        if (mDrawLine) {
            int lineCount = mMaxCount - 1;
            for (int lLoop = 0; lLoop < lineCount; lLoop++) {
                float drawXStart = startX + mStrokeRadius + dp2px(mGap) + (lLoop * g);
                float drawXEnd = startX + g - mStrokeRadius - dp2px(mGap) + (lLoop * g);
                mLineRect.left = drawXStart;
                mLineRect.right = drawXEnd;
                canvas.drawRect(mLineRect, mLinePaint);
            }
        }
    }

    private void drawTextVer(String name,Canvas canvas,float drawX){
        for(int i=0;i<name.length();i++){
            String c=Character.toString(name.charAt(i));
            mTextPaint.getTextBounds(c, 0, 1, mTextRect);
            float temp=mTextY+i*15f;
            canvas.drawText(c, drawX - mTextRect.width() / 4.0f, temp, mTextPaint);
        }
    }

    private int measure(int measureSpec, boolean isWidth) {
        int result;
        int mode = MeasureSpec.getMode(measureSpec);
        int size = MeasureSpec.getSize(measureSpec);
        int padding = isWidth ? getPaddingLeft() + getPaddingRight() : getPaddingTop() + getPaddingBottom();
        if (mode == MeasureSpec.EXACTLY) {
            result = size;
        } else {
            result = isWidth ? getSuggestedMinimumWidth() : getSuggestedMinimumHeight();
            result += padding;
            if (mode == MeasureSpec.AT_MOST) {
                if (isWidth) {
                    result = Math.max(result, size);
                } else {
                    result = Math.min(result, size);
                }
            }
        }
        return result;
    }

    @Override
    protected int getSuggestedMinimumWidth() {
        Log.e(TAG, "getSuggestedMinimumWidth : " + (mStrokeRadius * 2));
        return (int) (mStrokeRadius * 2);
    }

    @Override
    protected int getSuggestedMinimumHeight() {
        return DEFAULT_HEIGHT;
    }


    public void setIndicateSteps(List<Operator> list) {
        mSteps.clear();
        mSteps1.clear();
        for (Operator operator : list) {
            if (TextUtils.equals(operator.getName(), Constant.ACTION_NAME_JSC)) {
                this.mSteps.add(operator.getName()+operator.getValue());
            } else {
                this.mSteps.add(operator.getName());
            }
            mSteps1.add(Integer.toString(operator.getNum()));
        }
        setCurrentIndex(list.size(), 0);
    }

    public void setMode(int mode) {
        if (mode == MODE_BOTTOM) {
            this.mMode = MODE_BOTTOM;
        } else {
            this.mMode = MODE_TOP;
        }
        calcSize();
        invalidate();
    }

    public float dp2px(float dp) {
        final float scale = getResources().getDisplayMetrics().density;
        return dp * scale + 0.5f;
    }

    public float sp2px(float sp) {
        final float scale = getResources().getDisplayMetrics().scaledDensity;
        return sp * scale;
    }

}

